<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Adgeekgoogleapi extends CI_Controller
{
	function __construct()
	{
		parent::__construct();		
		$this->load->library('google-api-php-client/AdSenseHostAuth');
		define('LIB_DOC_ROOT', $_SERVER['DOCUMENT_ROOT'].'application/libraries/google-api-php-client/');
		
		//$this->load->library('google-api-php-client/src/contrib/Google_PlusService');
 	}

	function index(){
			try {
			  require_once LIB_DOC_ROOT."BaseExample.php";
			} catch (Exception $e) {
			  die('Missing requirement: ' . $e->getMessage() . "\n");
			}
		
			
			try {
			  // Build the list of supported actions.
			  $actions = $this->getSupportedActions();
			  // Go through API authentication.
			  //$auth = new AdSenseHostAuth();
			  //var_dump($this->adsensehostauth->authenticate('sample_user'));exit;
			  $this->adsensehostauth->authenticate('sample_user');
			  // To get rid of the code in the URL after the authentication.
			  if (isset($_GET['code'])) {
			    //header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
				  echo 'code is setted';exit;
			  }
			  // If the action is set dispatch the action if supported
			  if (isset($_GET["action"])) {
			    $action = $_GET["action"];
			    if (!in_array($action, $actions)) {
			      die('Unsupported action:' . $action . "\n");
			    }
			    // Render the required action.
			    require_once LIB_DOC_ROOT.'examples/' . $action . '.php';
			    $class = ucfirst($action);
			    $example = new $class($this->adsensehostauth->getAdSenseHostService());
			    $title = actionNameToWords($action) . ' example';
			    printHtmlHeader($title);
			    $example->render();
			    printHtmlFooter();
			    $this->adsensehostauth->refreshToken();
			  } else {
			    // Show the list of links to supported actions.
			    printHtmlHeader('AdSense Host API PHP usage examples.');
			    printIndex($actions);
			    printHtmlFooter();
			  }
			} catch (Exception $e) {
			  die('Runtime error: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
			}
	}

	function getSupportedActions() {
			  $actions = array();
			  $dirHandler = opendir(LIB_DOC_ROOT.'/examples');
			  while ($actionFile = readdir($dirHandler)) {
			    if (preg_match('/\.php$/', $actionFile)) {
			      $action = preg_replace('/\.php$/', '', $actionFile);
			      $actions[] = $action;
			    }
			  }
			  closedir($dirHandler);
			  asort($actions);
			  return $actions;
	}
}
		